/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webproject.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author jeong
 */
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
public class UploadServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        try {
//            /*
//             * TODO output your page here. You may use following sample code.
//             */
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet UploadServlet</title>");            
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<h1>Servlet UploadServlet at " + request.getContextPath() + "</h1>");
//            out.println("</body>");
//            out.println("</html>");
//        } finally {            
//            out.close();
//        }
        
    request.setCharacterEncoding("UTF-8");
    // 파일 저장 위치 설정.
    String contextRoot = getServletContext().getRealPath("/upload/");
   
    //String tempDir = contextRoot + "/temps" +"<br>";
    
    /**
        FileUpload 와 DiskFileUpload 클래스는 depricated 로 나와있어 톰캣에서 추천하는
        ServletFileUpload 와 DiskFileItemFactory 이 두클래스를 사용
    **/
    int sizeMax=1024*1024;
    if( ServletFileUpload.isMultipartContent(request) && request.getContentLength()<=sizeMax ){
        
        DiskFileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(factory);
  
        factory.setRepository(new File(contextRoot));    // 파일사이즈가 클경우 임시저장위치 지정(편의상
                                                         // 저장할위치와 똑같이 지정함)
        factory.setSizeThreshold(1024*100);              // 100kb 까지는 메모리에 저장
        upload.setSizeMax(sizeMax);                      // 1MB
        
        try{
            
            List files=upload.parseRequest(request);  
            Iterator<FileItem> iter=(files==null?null:files.iterator());
            
                while(iter!=null&& iter.hasNext()){
                    FileItem file=iter.next();
                    String param=file.getFieldName();
                    
                    if(file.isFormField()){
                        
                        System.out.println("param:"+param+"-value:"+file.getString("UTF-8")+"<br>"); 
                        
                    }else if(param.equals("upload")){
                        
                        String fileFullName=file.getName();
                        System.out.println("param:"+param+"-filename:"+fileFullName+"<br>");
                        
                        if(file.getSize()>0){
                            // 파일이름만 뽑아낸다
                            int index=fileFullName.lastIndexOf("\\");
                            if(index==-1) index=fileFullName.lastIndexOf("/");
                            String filename=file.getName().substring(index+1);
                            // 파일 저장.
                            File saveFile=new File(contextRoot,filename);
                                // 디렉토리 체크.
                                if(!saveFile.exists()) {
                                    saveFile.mkdirs();
                                }
                            
                                System.out.println("<h1>"+saveFile.getAbsolutePath()+"</h1>");
                                file.write(saveFile);
                        }
                    }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
        
        
    }
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
